'use server';

import View from './view';
import { notFound, forbidden, unauthorized } from 'next/navigation';
import { checkAuthServer } from '@/lib/api/auth';
import { fetchBoard, fetchBoardList } from '@/lib/api/forum/board';
import { fetchPostData } from '@/lib/api/forum/post';
import { getTokenData, checkPermission } from '@/lib/utils/server';
import { TokenData } from '@/types/response/common';
import PermissionDenied from '@/app/(main)/(forum)/board/_component/PermissionDenied';

export default async function PostEdit({ params }: { params: Promise<{ id: string }> })
{
	const { id } = await params;

	if (!/^\d+$/.test(id)) {
		return forbidden();
	}

	let tokenData: TokenData|null;

	try {

		if (!await checkAuthServer()) {
			throw Error;
		}

		// 회원 정보 조회
		tokenData = await getTokenData();
		if (!tokenData) {
			throw Error;
		}
	} catch {
		return unauthorized();
	}

	try {

		// 게시글 정보 조회
		const post = await fetchPostData(Number(id));

		if (!post.success || !post.data) {
			throw Error;
		}

		// 게시판 상세 조회
		const board = await fetchBoard(post.data.boardCode);
		if (!board.success || !board.data) {
			throw Error;
		}

		// 게시글 작성 권한 확인 (본인 글이면 스킵)
		if (Number(tokenData.id) !== post.data.memberID) {
			if (!await checkPermission(board.data.boardMeta.permission.postWrite, board.data.boardManager)) {
				return <PermissionDenied _board={board.data} />;
			}
		}

		// 게시판 목록 조회
		const boardList = await fetchBoardList(board.data.boardGroup.code);

		if (!boardList.success || !boardList.data) {
			throw Error;
		}

		return (
			<View _boardList={boardList.data} _board={board.data} _post={post.data} />
		);
	} catch {
		return notFound();
	}
}